<script setup>
import { reactive, ref, onUnmounted } from 'vue';
import router from '@/router';
import loginApi from '@/api/login_api.js';
import usersApi from '@/api/users_api.js';
import { ElMessage } from 'element-plus';

const activeIndex = ref('1');

// 当前登录管理员
const loginAdmin = ref({ realName: "未登录" });

// 获取管理员信息
async function getLogin() {
  const token = localStorage.getItem('token');
  if (!token) router.push('/login');
  try {
    const res = await loginApi.logininfo();
    loginAdmin.value = res;
  } catch (error) {
    console.error(error);
  }
}
getLogin();

// 左侧菜单数据
const menuData = ref([
  { name: '用户管理', icon: 'User', children: [
      { name: '管理列表', icon: 'Avatar', path: '/users' },
      { name: '用户列表', icon: 'UserFilled', path: '/user' }
    ] },
  { name: '商品管理', icon: 'ShoppingCart', children: [
      { name: '商品分类', icon: 'List', path: '/categories' },
      { name: '商品列表', icon: 'Goods', path: '/products' }
    ]
  },
  { name: '订单管理', icon: 'Document', children: [
      { name: '订单列表', icon: 'Document', path: '/orders' },
      { name: '订单统计', icon: 'DataAnalysis', path: '/orderStatistics' } // 添加这一行
    ] },
  { name: '购物车/收藏', icon: 'ShoppingBag', children: [{ name: '购物车列表', icon: 'ShoppingCart', path: '/shoppingCar' }] },
  { name: '评论管理', icon: 'ChatDotRound', children: [{ name: '评论列表', icon: 'ChatLineRound', path: '/comments' }] },
  { name: '主页', icon: 'HomeFilled', children: [{ name: '回到主页', icon: 'Promotion', path: '/' }] },
]);

// 左侧菜单动作
function handleMenu(key){
  if(key) router.push(key);
}

// 用户下拉菜单点击
function handleSelect(key){
  if(key === 'logout') logout();
  else if (key === '1-1') showEditInfoDialog();
  else if (key === '1-2') showResetPasswordDialog();
}

// 退出登录
function logout(){
  localStorage.removeItem('token');
  router.push('/login');
}

// 左侧菜单折叠
const isCollapse = ref(false);

// 编辑信息对话框相关
const editInfoDialogVisible = ref(false);
const editInfoForm = ref({
  // userId: '',
  username: '',
  realName: '',
  // password: '',
  email: '',
  school: '',
  studentId: '',
  phone: '',
  photo: '',


});
// 头像上传成功处理
const handleAvatarSuccess = (response, uploadFile) => {
  // 假设后端返回的格式为 {code: 200, data: "图片URL"}
  if (response.code === 200) {
    editInfoForm.value.photo = response.data;
    ElMessage.success('头像上传成功');
  } else {
    ElMessage.error('头像上传失败');
  }
}

// 上传前检查文件
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('头像必须是 JPG 或 PNG 格式!');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像大小不能超过 2MB!');
    return false;
  }
  return true;
}


function showEditInfoDialog() {
  editInfoForm.value = {
    userId: loginAdmin.value.userId || '',
    username: loginAdmin.value.username || '',
    realName: loginAdmin.value.realName || '',
    password: loginAdmin.value.password || '',
    email: loginAdmin.value.email || '',
    school: loginAdmin.value.school || '',
    studentId: loginAdmin.value.studentId || '',
    phone: loginAdmin.value.phone || '',
    photo: loginAdmin.value.photo || ''
  };
  editInfoDialogVisible.value = true;
}

async function submitEditInfo() {
  try {
    await usersApi.edit(editInfoForm.value);
    ElMessage.success('信息更新成功');
    editInfoDialogVisible.value = false;
    loginAdmin.value.username = editInfoForm.value.username;
    loginAdmin.value.realName = editInfoForm.value.realName;
    loginAdmin.value.email = editInfoForm.value.email;
    loginAdmin.value.school = editInfoForm.value.school;
    loginAdmin.value.studentId = editInfoForm.value.studentId;
    loginAdmin.value.phone = editInfoForm.value.phone;
    loginAdmin.value.photo = editInfoForm.value.photo;
    router.go(0);
  } catch (error) {
    console.error(error);
    ElMessage.error('信息更新失败');
  }
}

// 重置密码对话框相关
const resetPasswordDialogVisible = ref(false);
const resetPasswordForm = reactive({
  username: '',
  emailCode: '',
  newPassword: '',
  confirmPassword: ''
});

// 邮箱验证码相关
const isSendingCode = ref(false);
const countdown = ref(0);
let timer = null;

function showResetPasswordDialog() {
  resetPasswordForm.username = loginAdmin.value.username || '';
  resetPasswordForm.emailCode = '';
  resetPasswordForm.newPassword = '';
  resetPasswordForm.confirmPassword = '';
  resetPasswordDialogVisible.value = true;

  countdown.value = 0;
  isSendingCode.value = false;
  if (timer) clearInterval(timer);
}

async function sendEmailCode() {
  if (!resetPasswordForm.username) {
    ElMessage.warning('请输入用户名');
    return;
  }
  if (isSendingCode.value) return;

  try {
    isSendingCode.value = true;
    await loginApi.sendEmailCode({ username: resetPasswordForm.username });
    ElMessage.success('验证码已发送至您的邮箱，请注意查收');

    countdown.value = 60;
    timer = setInterval(() => {
      if (countdown.value > 0) countdown.value--;
      else {
        clearInterval(timer);
        timer = null;
        isSendingCode.value = false;
      }
    }, 1000);
  } catch (error) {
    console.error(error);
    ElMessage.error('发送失败');
    isSendingCode.value = false;
  }
}

async function submitResetPassword() {
  if (!resetPasswordForm.username || !resetPasswordForm.emailCode || !resetPasswordForm.newPassword || !resetPasswordForm.confirmPassword) {
    ElMessage.warning('请完整填写信息');
    return;
  }

  if (resetPasswordForm.newPassword !== resetPasswordForm.confirmPassword) {
    ElMessage.error('两次输入的新密码不一致');
    return; // 弹窗不关闭
  }

  try {
    await loginApi.resetPassword({
      username: resetPasswordForm.username,
      emailCode: resetPasswordForm.emailCode,
      newPassword: resetPasswordForm.newPassword
    });

    ElMessage.success('密码重置成功，请重新登录');

    // 清理表单和倒计时
    resetPasswordForm.emailCode = '';
    resetPasswordForm.newPassword = '';
    resetPasswordForm.confirmPassword = '';
    countdown.value = 0;
    isSendingCode.value = false;
    if (timer) { clearInterval(timer); timer = null; }

    resetPasswordDialogVisible.value = false;

    // 自动退出登录
    localStorage.removeItem('token');
    router.push('/login');
  } catch (error) {
    console.error(error);
    // 弹窗不关闭，表单保持
  }
}

// 关闭对话框时的清理
function handleResetPasswordDialogClose() {
  resetPasswordDialogVisible.value = false;
  if (timer) { clearInterval(timer); timer = null; }
  countdown.value = 0;
  isSendingCode.value = false;
}

// 页面卸载清理定时器
onUnmounted(() => { if (timer) clearInterval(timer); });
</script>

<template>
  <div class="common-layout">
    <el-container>
      <!-- 头部 -->
      <el-header>
        <el-menu :default-active="activeIndex"
                 class="el-menu-demo"
                 mode="horizontal"
                 :ellipsis="false"
                 background-color="#f3f7ff"
                 text-color="#393939"
                 active-text-color="#ffd04b"
                 @select="handleSelect">

          <el-menu-item index="0">
            <img style="height: 80%" src="@/assets/logo.png" alt="多转转" />
            <span style="padding-left: 50px; font-size: 24px; color:#bd2525;">
            多转转校园二手商城管理系统
          </span>
          </el-menu-item>

          <div class="flex-grow" />

          <!-- 修改后的代码 -->
          <el-sub-menu index="1">
            <template #title>
              <div class="user-info">
                <img
                    v-if="loginAdmin?.photo"
                    :src="loginAdmin.photo"
                    class="user-avatar"
                    alt="用户头像"
                />
                <el-icon v-else class="default-avatar"><User /></el-icon>
                <span class="username">{{ loginAdmin?.realName || '未登录' }}</span>
              </div>
            </template>
            <el-menu-item index="1-1">修改信息</el-menu-item>
            <el-menu-item index="1-2">重置密码</el-menu-item>
            <el-menu-item index="logout">退出<el-icon><SwitchButton /></el-icon></el-menu-item>
          </el-sub-menu>

        </el-menu>
      </el-header>

      <!-- 内容区 -->
      <el-container>
        <!-- 左侧菜单 -->
        <el-aside :width="200">
          <el-menu
              active-text-color="#ff7f9e"
              background-color="#fff0f5"
              text-color="#d65a6c"
              class="el-menu-vertical-demo"
              default-active="/"
              :collapse="isCollapse"
              @select="handleMenu">

            <el-sub-menu v-for="(menu, index) in menuData" :key="index" :index="index.toString()">
              <template #title>
                <component :is="menu.icon" class="icons" style="width:1em;height:1em;margin-right:8px" />
                <span>{{ menu.name }}</span>
              </template>
              <el-menu-item v-for="(child, ind) in menu.children" :key="ind" :index="child.path">
                <component :is="child.icon" />
                <span>{{ child.name }}</span>
              </el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-aside>

        <!-- 右侧内容 -->
        <el-main>
          <router-view />
        </el-main>
      </el-container>
    </el-container>
  </div>

  <!-- 在编辑信息对话框中添加头像上传 -->
  <el-dialog v-model="editInfoDialogVisible" title="修改个人信息" width="500px">
    <el-form :model="editInfoForm" label-width="100px">
      <el-form-item label="用户名"><el-input v-model="editInfoForm.username" /></el-form-item>
      <el-form-item label="真实姓名"><el-input v-model="editInfoForm.realName" /></el-form-item>
      <el-form-item label="手机号"><el-input v-model="editInfoForm.phone" /></el-form-item>
      <el-form-item label="邮箱"><el-input v-model="editInfoForm.email" /></el-form-item>
      <el-form-item label="学校"> <el-input v-model="editInfoForm.school" /></el-form-item>
      <el-form-item label="学号"><el-input v-model="editInfoForm.studentId" /></el-form-item>

      <!-- 添加头像上传 -->
      <el-form-item label="头像">
        <el-upload
            class="avatar-uploader"
            action="/api/upload/file"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
          <img v-if="editInfoForm.photo" :src="editInfoForm.photo" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="editInfoDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitEditInfo">保存</el-button>
    </template>
  </el-dialog>


  <!-- 重置密码对话框 -->
  <el-dialog v-model="resetPasswordDialogVisible" title="重置密码" width="500px" @close="handleResetPasswordDialogClose">
    <el-form :model="resetPasswordForm" label-width="100px">
      <el-form-item label="用户名">
        <el-input v-model="resetPasswordForm.username" disabled />
      </el-form-item>
      <el-form-item label="邮箱验证码">
        <el-input v-model="resetPasswordForm.emailCode" placeholder="请输入邮箱验证码">
          <template #append>
            <el-button @click="sendEmailCode" :disabled="isSendingCode || countdown > 0">
              {{ countdown > 0 ? `${countdown}秒后重发` : '发送验证码' }}
            </el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="新密码">
        <el-input v-model="resetPasswordForm.newPassword" type="password" placeholder="请输入新密码" />
      </el-form-item>
      <el-form-item label="确认密码">
        <el-input v-model="resetPasswordForm.confirmPassword" type="password" placeholder="请再次输入新密码" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleResetPasswordDialogClose">取消</el-button>
      <el-button type="primary" @click="submitResetPassword">保存</el-button>
    </template>
  </el-dialog>
</template>

<style>
.flex-grow { flex-grow: 1; }
.common-layout, .el-container { height: 100%; }
.el-header {
  --el-header-padding: 0;
  --el-header-height: 80px;
  box-sizing: border-box;
  flex-shrink: 0;
  height: var(--el-header-height);
  padding: var(--el-header-padding);
}
.el-menu--horizontal { height: 80px; }
.el-aside { background-color: #f3efef; }
.el-main { padding: 20px; }
.el-menu { border-width: 0px; }
.el-menu-item { font-size: 16px; }
.el-menu-demo { box-shadow: 0 2px 4px rgba(244,64,64,0.35); }
.el-sub-menu__title { font-size: 16px; }
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.user-info {
  display: flex;
  align-items: center;
  height: 100%;
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-right: 8px;
  object-fit: cover;
}

.default-avatar {
  width: 32px;
  height: 32px;
  margin-right: 8px;
}

.username {
  vertical-align: middle;
}


</style>

